import { getCompanyInfoData, updateCompanyInfoData } from "@/api/company/info"
import { CompanyInfo, UpdateCompanyInfo } from "@/api/company/types/info"
import { defineStore } from "pinia"
import { reactive } from "vue"
import { pinia } from "@/store"

type baseCompanyInfo = Omit<CompanyInfo, "userVO">

export const useCompanyStore = defineStore("company", () => {
  const baseCompanyInfo = reactive<baseCompanyInfo>({
    id: "",
    companyShortName: null,
    companyName: null,
    companyDescription: null,
    companyPictures: null,
    companyAddress: [],
    companyEmail: null,
    companyPhone: null,
    companyLegal: null,
    companyRegisterCapital: null,
    companyRegisterDate: null
  })

  const getCompanyInfo = async () => {
    const { data } = await getCompanyInfoData()
    for (const attr of Object.keys(baseCompanyInfo)) {
      if (Object.prototype.hasOwnProperty.call(data, attr)) {
        if (attr === "companyAddress") {
          // @ts-expect-error
          baseCompanyInfo[attr] = data[attr]?.map((item: string) => String(item))
        } else {
          // @ts-expect-error
          baseCompanyInfo[attr] = data[attr]
        }
      }
    }
  }

  const updateCompanyInfo = async (_data: UpdateCompanyInfo) => {
    return new Promise<boolean>((resolve, _) => {
      const data = Object.assign(_data, { id: baseCompanyInfo.id })
      updateCompanyInfoData(data)
        .then(() => {
          return getCompanyInfo
        })
        .then(() => resolve(true))
    })
  }

  return { baseCompanyInfo, getCompanyInfo, updateCompanyInfo }
})

export function useCompanyStoreHook() {
  return useCompanyStore(pinia)
}
